#!/usr/bin/env python
# _*_ coding: utf-8 _*_
# @Time : 2020/8/1 19:17
# @Author : LZQ
# @Version：V 0.1
# @File : tree.py
# @desc :
import sqlalchemy
from flask_sqlalchemy import Pagination
from app.models import Category

def get_tree(*kwargs):
    tree = []
    list1 = []
    list2 = []
    list3 = []
    categorys = None
    if kwargs:
        categorys = kwargs[0]
    for category in categorys:
        if category.cat_level==0:
            list1.append(category)
        if category.cat_level==1:
            list2.append(category)
        if category.cat_level==2:
            list3.append(category)
    for level_1 in list1:
        level_1_dict=level_1.to_dict()
        level_1_dict['children'] = []
        for level_2 in list2:
            level_2_dict = level_2.to_dict()
            level_2_dict['children'] = []
            for level_3 in list3:
                if level_3.cat_pid==level_2.cat_id:
                    level_2_dict['children'].append(level_3.to_dict())
            if level_2.cat_pid == level_1.cat_id:
                level_1_dict['children'].append(level_2_dict)
        tree.append(level_1_dict)
    return tree